<template>
  <!-- 限制号源查询 -->
  <div
    class="limit-container">
    <div class="ky-form_fixed">
      <el-card shadow="" class="ky-card ky-card-xs ky-card-hdbg">
        <el-form ref="ruleForm" :model="formData" :inline="true" label-width="80px" class="ky-form-inline ky-form-inline-sm" :rules="rules">
          <el-form-item label="医院名称" prop="hospitalCode">
            <el-select size="small" v-model="formData.hospitalCode" filterable placeholder="请选择" @change="handleChange('hospital')">
              <el-option
                v-for="(item,index) in mx_hospitalList"
                :key="index"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="影像区域">
            <el-select size="small" v-model="formData.depArea" placeholder="请选择" clearable collapse-tags @change="handleChange('depArea')">
              <el-option
                v-for="(item,index) in depAreaOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查部门">
            <el-select size="small" v-model="formData.dep" placeholder="请选择" clearable collapse-tags @change="handleChange('dep')">
              <el-option
                v-for="(item,index) in scheduledDepOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查设备">
            <el-select size="small" v-model="formData.modality" placeholder="请选择" clearable collapse-tags @change="handleChange('modality')">
              <el-option
                v-for="(item,index) in modalityOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查机房">
            <el-select size="small" v-model="formData.checkRoom" placeholder="请选择" clearable collapse-tags>
              <el-option
                v-for="(item,index) in checkRoomOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="患者类型">
            <el-select size="small" v-model="formData.patType" placeholder="请选择" clearable collapse-tags>
              <el-option
                v-for="(item,index) in patTypeOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="预约来源">
            <el-select size="small" v-model="formData.appointmentType" placeholder="请选择" clearable collapse-tags>
              <el-option
                v-for="(item,index) in appointmentTypeOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查方式">
            <el-select size="small" v-model="formData.checkType" placeholder="请选择" clearable collapse-tags>
              <el-option
                v-for="(item,index) in checkTypeOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查部位">
            <el-select size="small" v-model="formData.dengjipart" placeholder="请选择" filterable clearable collapse-tags>
              <el-option
                v-for="(item,index) in dengjipartOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查项目">
            <virtualselect
              :data="checkposOptions"
              v-model="formData.checkpos"
              placeholder="请选择"
              clearable
              @change="handleChange('checkpos')"
            ></virtualselect>
            <!-- <el-select size="small" v-model="formData.checkpos" placeholder="请选择" filterable clearable collapse-tags>
              <el-option
                v-for="(item,index) in checkposOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select> -->
          </el-form-item>
          <el-form-item label="查询日期" prop="appointmentDate">
            <el-date-picker
              v-model="formData.appointmentDate"
              type="date"
              :clearable="false"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="m-l-0 click-button" size="small" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="mar-l-10 click-button" size="small" icon="el-icon-refresh-right" @click="resetParam" plain>重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div
      class="table_box"
      v-loading="loading"
    >
      <template v-if="tableData.length>0">
        <el-card
          shadow="hover"
          class="ky-card ky-card-hdbg ky-mt10"
          v-for="(item, index) in tableData"
          :key="index"
        >
          <div class="content-title" @click="checkRoomChange(index,item)">
            <span class="tit">{{item.checkroomAll}}</span>
            <!-- <span class="tit">机房：{{item.checkRoom}}</span> -->
            <span class="tag tag4">总号源数：<b>{{item.appointmentNum}}</b></span>
            <span class="tag" :class="item.canNum==0?'tag1':'tag2'">可预约号源数：<b>{{item.canNum}}</b></span>
            <span class="tag">已预约号源数：<b>{{item.callNumTotal}}</b></span>
            <div class="ky-fr">
              <span class="time">{{item.date}}</span>
              <span v-show="!item.show">展开详情<i class="el-icon-arrow-right"></i></span>
              <span v-show="item.show">收起详情<i class="el-icon-arrow-up"></i></span>
            </div>
          </div>
          <el-table
            v-if="item.show"
            ref="table"
            size="medium"
            :data="item.appointmentLists"
            style="width: 100%;margin-top: 12px;"
            border
            :row-class-name="tableRowClassName"
            class="ky-table"
          >
            <el-table-column type="index" width="50" label="序号"></el-table-column>
            <!-- <el-table-column label="院区/部门/设备/机房" width="260">
              <template slot-scope="scope">
                <span>{{scope.row.depArea}}</span>/
                <span>{{scope.row.dep}}</span>/
                <span>{{scope.row.modality}}</span>/
                <span>{{scope.row.checkRoom}}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="时段" width="150">
              <template slot-scope="scope">
                <span>{{scope.row.beginTime}}</span> -
                <span>{{scope.row.endTime}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="" label="总号源数" width="100">
              <template slot-scope="scope">
                <span class="checkNum">{{checkNumCal(scope.row)}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="lessNum" label="可预约数" width="100">
              <template slot-scope="scope">
                <span class="lessNum">{{scope.row.lessNum}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="callNum" label="已预约数" width="100">
              <template slot-scope="scope">
                <span class="callNum">{{scope.row.callNum}}</span>
              </template>
            </el-table-column>
            <el-table-column label="限制条件" min-width="200">
              <template slot-scope="scope">
                <template v-if="scope.row.invalidType>0">
                  <span>{{invalidTypeFlr(scope.row.invalidType)}} {{scope.row.invalidType>0?'：':''}}</span>
                  <span class="fc_orange">{{scope.row.invalidReason}}</span>
                </template>
                <template v-else-if="scope.row.appointmentFilterListDmbs != null">
                  <span
                    v-for="(item) in scope.row.appointmentFilterListDmbs"
                    :key="item.id"
                  ><span class="dmbs_lab">{{item.remark1}}</span>={{item.parametersValues}}，</span>
                </template>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="hospitalName" label="医院" min-width="170"></el-table-column> -->
            <!-- <el-table-column prop="depArea" label="院区"></el-table-column>
            <el-table-column prop="dep" label="部门"></el-table-column>
            <el-table-column prop="modality" label="设备"></el-table-column>
            <el-table-column prop="checkRoom" label="机房"></el-table-column> -->
          </el-table>
        </el-card>
      </template>
      <div v-else class="ky-listnone" style="padding: 100px 0;">【{{formData.appointmentDate}}】暂无号源！</div>
    </div>
    <div class="footer_box">
      <div class="ft_wrap">
        <span class="tag tag4">机房数：<b>{{tableData.length}}</b></span>
        <span class="tag tag4">总号源数：<b>{{appoTotalNum}}</b></span>
        <span class="tag tag2">总可预约号源数：<b>{{canTotalNum}}</b></span>
        <span class="tag">总已预约号源数：<b>{{callTotalNum}}</b></span>
      </div>
    </div>
  </div>
</template>

<script>
import {
  postappointmentlistdmbcheckroomsummarylist,
  getDepAreaList,
  getDepList,
  getModalityList,
  getCheckRoomList,
  getBigPartList,
  getHisCheckroomgetSmallpartlist
} from '@/api/api'
import { Options } from '@/utils/constant'
// import paginationCont from '@/components/Pagination/index'
import { dateFormatter } from '@/utils/validate'
import virtualselect from '@/components/virtualselect/index'
export default {
  name: '',
  components: { virtualselect },
  data() {
    return {
      loading: false,
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      appoTotalNum: 0, // 号源总数
      canTotalNum: 0, // 可预约总数
      callTotalNum: 0, // 已预约总数
      tableData: [],
      formData: {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: '',
        depArea: '',
        modality: '',
        checkRoom: '',
        appointmentDate: dateFormatter(new Date().getTime(), false),
        patType: '',
        appointmentType: '',
        checkType: '',
        dengjipart: '',
        checkpos: ''
      },
      rules: {
        hospitalCode: { required: true, message: '请选择医院', trigger: 'change' },
        appointmentDate: { required: true, message: '请选择检查日期', trigger: 'change' }
      },
      depAreaOptions: [],
      scheduledDepOptions: [],
      modalityOptions: [],
      checkRoomOptions: [],
      patTypeOptions: Options.patientTypeItemOptions.map(item => item.label) || [], // 患者类型(住院、门诊、体检、绿检、急诊、外院)
      appointmentTypeOptions: ['前台登记', '临床预约', '移动预约', '自助预约'], // 预约来源：前台登记、临床预约、移动预约、自助预约
      checkTypeOptions: Options.examMethodItemOptions || [], // 检查方式（平扫、增强等）
      dengjipartOptions: [], // 大部位
      checkposOptions: [] // 小部位
    }
  },
  created() {
    this.$getHospitalList()
  },
  async mounted() {
    this.formData.hospitalCode = this.$store.state.user.hospitalCode || ''
    try {
      await this.getDepAreaOptions()
      this.getScheduledDepOptions()
      this.getModalityOptions()
      this.getCheckRoomOptions()
      this.getBigPartOptions()
      this.getSmallPartOptions()
    } catch (err) {
      console.log(err)
    }
    this.search()
  },
  methods: {
    resetParam() {
      // 重置
      this.formData = {
        hospitalCode: this.$store.state.user.hospitalCode,
        dep: '',
        depArea: '',
        modality: '',
        checkRoom: '',
        appointmentDate: dateFormatter(new Date().getTime(), false),
        patType: '',
        appointmentType: '',
        checkType: '',
        dengjipart: '',
        checkpos: ''
      }
    },
    search() {
      // 查询
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.currentPage = 1
          this.fetchData()
        }
      })
    },
    changePagenation() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.fetchData()
        }
      })
    },
    fetchData() {
      let data = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea,
        dep: this.formData.dep,
        modality: this.formData.modality,
        checkRoom: this.formData.checkRoom,
        patType: this.formData.patType,
        appointmentType: this.formData.appointmentType,
        checkType: this.formData.checkType,
        dengjipart: this.formData.dengjipart,
        checkpos: this.formData.checkpos,
        appointmentDate: dateFormatter(this.formData.appointmentDate, false),
        pageSize: this.pageSize, // 页面大小
        pageNumber: this.currentPage // 页码
      }
      this.loading = true
      postappointmentlistdmbcheckroomsummarylist(data).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          const _list = res.content.list
          const crTxtArr = []
          let atNum = 0
          let ctNum = 0
          let calltNum = 0
          _list.forEach((item, index) => {
            // if (index === 0) {
            //   item.show = true
            // } else {
            // }
            item.show = false
            const appoList = item.appointmentLists
            item.callNumTotal = this.countTotal(appoList, 'callNum')
            atNum += item.appointmentNum
            ctNum += item.canNum
            calltNum += item.callNumTotal

            /**
             * <span>{{scope.row.depArea}}</span>/
                <span>{{scope.row.dep}}</span>/
                <span>{{scope.row.modality}}</span>/
                <span>{{scope.row.checkRoom}}</span>
             */
            if (appoList.length > 0) {
              const appo = appoList[0]
              item.checkroomAll = `${appo.depArea + '-' + appo.dep + '-' + appo.modality + '-' + appo.checkRoom}`
            }
            crTxtArr.push(item.checkRoom)
          })
          this.appoTotalNum = atNum
          this.canTotalNum = ctNum
          this.callTotalNum = calltNum
          this.tableData = _list
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 计算对象数组的某个字段合计
    countTotal(arr, keyName) {
      let $total = 0
      $total = arr.reduce(function (total, currentValue, currentIndex, arr) {
        return currentValue[keyName] ? (total + currentValue[keyName]) : total
      }, 0)
      // console.log('$total====', $total)
      return $total
    },
    getBigPartOptions() {
      /* 检查部位，大部位 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        Dep: this.formData.dep
      }
      return new Promise(async resolve => {
        await getBigPartList(params).then((res) => {
          if (res.code === 10000) {
            this.dengjipartOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getSmallPartOptions() {
      /* 检查项目，小部位 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        Dep: this.formData.dep
      }
      return new Promise(async resolve => {
        await getHisCheckroomgetSmallpartlist(params).then((res) => {
          if (res.code === 10000) {
            let checkposOptions = res.content.list
            let resultCheckPosOption = []
            checkposOptions.forEach(item => {
              let checkPosItem = {}
              checkPosItem.value = item
              checkPosItem.label = item
              resultCheckPosOption.push(checkPosItem)
            })
            this.checkposOptions = resultCheckPosOption
            resolve(res)
          }
        })
      })
    },
    getDepAreaOptions() {
      /* 影像区域列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode
      }
      return new Promise(async resolve => {
        await getDepAreaList(params).then((res) => {
          if (res.code === 10000) {
            this.depAreaOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getScheduledDepOptions() {
      /* 检查部门列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea
      }
      return new Promise(async resolve => {
        await getDepList(params).then((res) => {
          if (res.code === 10000) {
            this.scheduledDepOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getModalityOptions() {
      /* 检查设备列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea,
        dep: this.formData.dep
      }
      return new Promise(async resolve => {
        await getModalityList(params).then((res) => {
          if (res.code === 10000) {
            this.modalityOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getCheckRoomOptions() {
      /* 检查机房列表 */
      let params = {
        hospitalCode: this.formData.hospitalCode,
        depArea: this.formData.depArea,
        dep: this.formData.dep,
        modality: this.formData.modality
      }
      return new Promise(async resolve => {
        await getCheckRoomList(params).then((res) => {
          if (res.code === 10000) {
            this.checkRoomOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    async handleChange(val) {
      switch (val) {
        case 'hospital':
          this.depAreaOptions = []
          this.scheduledDepOptions = []
          this.modalityOptions = []
          this.checkRoomOptions = []
          this.formData.depArea = ''
          this.formData.dep = ''
          this.formData.modality = ''
          this.formData.checkRoom = ''
          this.formData.dengjipart = ''
          this.formData.checkpos = ''
          this.tableData = []
          this.totalCount = 0
          try {
            await this.getDepAreaOptions()
            this.getScheduledDepOptions()
            this.getModalityOptions()
            this.getCheckRoomOptions()
            this.search()
            this.getBigPartOptions()
            this.getSmallPartOptions()
          } catch (err) {
            console.log(err)
          }
          break
        case 'depArea':
          this.scheduledDepOptions = []
          this.modalityOptions = []
          this.checkRoomOptions = []
          this.formData.dep = ''
          this.formData.modality = ''
          this.formData.checkRoom = ''
          try {
            await this.getScheduledDepOptions()
            this.getModalityOptions()
            this.getCheckRoomOptions()
          } catch (err) {
            console.log(err)
          }
          break
        case 'dep':
          this.modalityOptions = []
          this.checkRoomOptions = []
          this.formData.modality = ''
          this.formData.checkRoom = ''
          this.formData.dengjipart = ''
          this.formData.checkpos = ''
          try {
            await this.getModalityOptions()
            await this.getCheckRoomOptions()
            this.getBigPartOptions()
            this.getSmallPartOptions()
          } catch (err) {
            console.log(err)
          }
          break
        case 'modality':
          this.checkRoomOptions = []
          this.formData.checkRoom = ''
          try {
            await this.getCheckRoomOptions()
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    },
    // 显示切换
    checkRoomChange(index, row) {
      // this.tableData.forEach(item => {
      //   item.show = false
      // })
      this.tableData[index].show = !this.tableData[index].show
      // this.tableData = JSON.parse(JSON.stringify(this.tableData))
      // this.$refs.scrollbox.scrollTo(500, 300)
    },
    // getFilterDmbsText(arr) {
    //   let txt = ''
    //   if (arr != null) {
    //     console.log(arr != null)
    //     arr.forEach(item => {
    //       txt += `${item.remark1}=${item.parametersValues};`
    //     })
    //   }
    //   return txt
    // },
    tableRowClassName({ row }) {
      // console.log(row)
      if (row.invalidType > 0) {
        return 'danger_row'
      }
      return ''
    },
    // 计算总检查号源数
    checkNumCal(row) {
      return row.checkNum + row.reserveNum + row.addNum + row.callNum
    },
    invalidTypeFlr(val) {
      const invType = ['', '时段限制', '时段条件限制', '机房部位限制', '预约规则限制']
      return invType[val]
    }
  }
}
</script>
<style lang='scss' scoped>
.table_box{
  min-height: 400px;
  padding: 0 16px 16px;
}
.content-title{
  margin-left:4px;
  font-family: PingFangSC-Medium, PingFang SC;
  color: rgba(0, 0, 0, 0.85);
  line-height: 34px;
  cursor: pointer;
  .tit{
    display: inline-block;
    min-width: 200px;
    font-size: 14px;
    margin-right: 20px;
  }
  .time{
    font-size: 14px;
    color: #999;
    margin-right: 10px;
  }
}
.tag{
  font-size: 14px;
  padding: 4px 10px;
  border-radius: 4px;
  background-color: rgba(26, 144, 255, 0.08);
  color: #1890FF;
}
.tag1{
  background-color: rgba(227, 116, 112, 0.08);
  color: #E37470;
}
.tag2{
  background-color: rgba(11, 214, 119, 0.08);
  color: #0bd677;
}
.tag3{
  background-color: rgba(255, 136, 24, 0.08);
  color: #FF8618;
}
.tag4{
  background-color: rgba(145, 147, 152, 0.08);
  color: #919398;
}
.dmbs_lab{
  color: #1890FF
}
.title_btn{
  margin-left: 20px;
}
.status_edit{
  color: #FF8618;
  cursor: pointer;
  margin-left: 10px;
  &:hover{
    color: #f19238
  }
}
.lessNum{
  font-weight: bold;
  color: #0bd677;
}
.callNum{
  font-weight: bold;
  color: #1890FF;
}

/deep/ .el-table .danger_row {
  background: rgba(227, 116, 112, 0.199);
}

.limit-container{
  position: relative;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
  /deep/ .ky-card .el-card__body{
    padding: 10px;
  }
}
.footer_box{
  width: 100%;
  position: fixed;
  bottom: 0px;
  z-index: 10;
  padding: 17px 0;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-left: -16px;
  .ft_wrap{
    padding: 0 20px 0 50px;
  }
}
.ky-form_fixed{
  position: sticky;
  top: 0px;
  z-index: 10;
  padding: 16px 16px 0;
  background-color: rgba(255,255,255,0.8);
  backdrop-filter: saturate(180%) blur(20px);
}

$appoSuccessColor: #0bd677;
$appoSuccessBgColor: rgba(11, 214, 119, 0.08);
$appoSuccessBrColor: rgba(11, 214, 112, 0.4);
$appoDefaultColor: #1890FF;
$appoDefaultBgColor: rgba(26, 144, 255, 0.08);
$appoDefaultBrColor: rgba(24, 143, 255, 0.4);
$appoDangerColor: #E37470;
$appoDangerBgColor: rgba(227, 116, 112, 0.08);
$appoDangerBrColor: rgba(235, 79, 79, 0.4);
$appoWarnColor: #FF8618;
$appoWarnBgColor: rgba(255, 136, 24, 0.08);
$appoWarnBrColor: rgba(255, 136, 24, 0.4);
$appoGreyColor: #919398;
$appoGreyBgColor: rgba(145, 147, 152, 0.08);
$appoGreyBrColor: rgba(145, 147, 152, 0.4);
.status_tag{
  display: inline-block;
  padding: 2px 6px;
  border-radius: 3px;
  border: solid 1px $appoDefaultBrColor;
  background-color: $appoDefaultBgColor;
  font-size: 12px;
  color: $appoDefaultColor;
}
.status_default{
  border-color: $appoDefaultBrColor;
  background-color: $appoDefaultBgColor;
  color: $appoDefaultColor;
}
.status_success{
  border-color: $appoSuccessBrColor;
  background-color: $appoSuccessBgColor;
  color: $appoSuccessColor;
}
.status_danger{
  border-color: $appoDangerBrColor;
  background-color: $appoDangerBgColor;
  color: $appoDangerColor;
}
.status_warn{
  border-color: $appoWarnBrColor;
  background-color: $appoWarnBgColor;
  color: $appoWarnColor;
}
.status_grey{
  border-color: $appoGreyBrColor;
  background-color: $appoGreyBgColor;
  color: $appoGreyColor;
}
</style>
